<!--
 * @Author: Dorange.Wang
 * @Date: 2021-05-19 15:41:40
 * @LastEditors: your name
 * @LastEditTime: 2021-06-24 15:57:19
 * @Description: file content
-->
<template>
  <el-dialog :visible="showVisible" center :show-close="false" width="1200px">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ isNew ? "新建HTTP方法" : "编辑HTTP方法" }}</span>
        <span
          class="el-icon-close g9 f26 poi"
          @click="showVisible = false"
        ></span>
      </div>
    </div>

    <div class="pl30 pr30">
      <el-form :model="formData" ref="form" label-width="120px">
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item
              label="服务方式"
              prop="type"
              :rules="[
                {
                  required: true,
                  message: '请选择服务方式',
                  trigger: 'change',
                },
              ]"
            >
              <el-select
                :disabled="!isNew"
                style="width: 100%"
                v-model="formData.type"
                placeholder="请选择服务方式"
                @change="handleTypeChange"
              >
                <el-option
                  v-for="(value, key) in SERVICE_TYPE_ENUM"
                  :key="key"
                  :value="key"
                  :label="value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="服务编码"
              prop="key"
              :rules="[
                {
                  required: true,
                  message: '服务编码不能为空',
                  trigger: 'change',
                },
              ]"
            >
              <!-- <template slot="label">服务编码
                <el-tooltip popper-class="custom-popper" :content="COMMON_CODE_REG_MSG" placement="top">
                  <i class="el-icon-question" />
                </el-tooltip>
              </template> -->
              <el-input
                :disabled="!isNew || formData.type !== SERVICE_TYPE_OTHER"
                v-model="formData.key"
                placeholder="请输入服务编码"
                :maxlength="28"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="服务名称"
              prop="name"
              :rules="[
                {
                  required: true,
                  message: '服务名称不能为空',
                  trigger: 'change',
                },
              ]"
            >
              <el-input
                v-model="formData.name"
                placeholder="请输入服务名称"
                :maxlength="64"
                show-word-limit
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="说明">
              <el-input
                type="textarea"
                v-model="formData.remark"
                placeholder="请输入说明"
                :maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="API请求" required>
              <el-row type="flex" align="middle">
                <el-form-item
                  class="method"
                  label=""
                  label-width="0px"
                  prop="method"
                  :rules="[
                    {
                      required: true,
                      message: '请选择请求方式',
                      trigger: 'change',
                    },
                  ]"
                >
                  <el-select
                    class="pct100"
                    v-model="formData.method"
                    placeholder="请选择请求方式"
                  >
                    <el-option
                      v-for="(value, key) in REQUEST_METHOD_ENUM"
                      :key="key"
                      :value="key"
                      :label="value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  prop="httpServiceId"
                  :rules="[
                    {
                      required: true,
                      message: '请选择第三方服务',
                      trigger: 'change',
                    },
                  ]"
                >
                  <el-select
                    filterable
                    clearable
                    style="width: 400px"
                    v-model="formData.httpServiceId"
                    placeholder="请选择第三方服务"
                  >
                    <el-option
                      v-for="item in httpServiceList"
                      :key="item.id"
                      :value="item.id"
                      :label="
                        getServiceUrl(item.settingList) +
                        '（' +
                        item.name +
                        '）'
                      "
                    />
                  </el-select>
                </el-form-item>

                <el-form-item
                  class="path"
                  label=""
                  label-width="0px"
                  prop="path"
                  :rules="[
                    {
                      required: true,
                      message: '路径不能为空',
                      trigger: 'change',
                    },
                  ]"
                >
                  <el-input
                    v-model="formData.path"
                    placeholder="请输入路径，以“/”开头"
                    :maxlength="128"
                    show-word-limit
                  >
                  </el-input>
                </el-form-item>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-tabs v-model="activeTab">
        <el-tab-pane label="输入参数" name="REQUEST">
          <el-tabs
            class="request-tabs"
            v-model="positionTab"
            tab-position="left"
          >
            <el-tab-pane label="Query" name="QUERY">
              <HttpReqTable ref="HttpQueryTable" />
            </el-tab-pane>
            <el-tab-pane label="Body" name="BODY">
              <HttpReqBody ref="HttpReqBody" />
            </el-tab-pane>
            <el-tab-pane label="Headers" name="HEADERS">
              <HttpReqTable ref="HttpHeaderTable" />
            </el-tab-pane>
          </el-tabs>
        </el-tab-pane>
        <el-tab-pane label="返回值" name="RESPONSE">
          <HttpResTable ref="HttpResTable" />
        </el-tab-pane>
      </el-tabs>
    </div>

    <div slot="footer" class="tr">
      <el-button @click="showVisible = false">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
      <el-button type="primary" @click="submit('debug')">保存并调试</el-button>
    </div>
    <HttpDebugModal
      ref="HttpDebugModal"
      :modelInfo="modelInfo"
    ></HttpDebugModal>
  </el-dialog>
</template>

<script>
import {
  SERVICE_TYPE_ENUM,
  REQUEST_METHOD_ENUM,
  HTTP_REQUEST_TAB_ENUM,
  REQUEST_BODY_TYPE_ENUM,
  REQUEST_PARAMS_POSITION_ENUM,
} from "@/utils/enum";
import HttpDebugModal from "./HttpDebug/HttpDebugModal";
import { COMMON_CODE_REG, COMMON_CODE_REG_MSG } from "@/utils/reg";

import {
  postHmhttprequestdefinition,
  putHmhttprequestdefinition,
} from "@/apis/paas/HmHttpRequestDefinitionController.js";
import {
  getHmhttpserviceInfo,
  getHmhttpservicePageList,
} from "@/apis/paas/HmHttpServiceController.js";
import HttpReqTable from "./HttpReqTable";
import HttpReqBody from "./HttpReqBody";
import HttpResTable from "./HttpResTable";

const defaultTab = Object.keys(HTTP_REQUEST_TAB_ENUM)[0];
const defaultPositionTab = Object.keys(REQUEST_PARAMS_POSITION_ENUM)[0];
const defaultBodyTypeTab = Object.keys(REQUEST_BODY_TYPE_ENUM)[0];

export default {
  name: "HttpModal",
  components: {
    HttpReqTable,
    HttpReqBody,
    HttpResTable,
    HttpDebugModal,
  },

  props: {
    modelInfo: {
      type: Object,
      default: () => {},
    },
  },

  data() {
    return {
      loading: false,
      SERVICE_TYPE_ENUM,
      SERVICE_TYPE_OTHER: "OTHER",
      REQUEST_METHOD_ENUM,
      HTTP_REQUEST_TAB_ENUM,
      REQUEST_PARAMS_POSITION_ENUM,
      REQUEST_BODY_TYPE_ENUM,
      COMMON_CODE_REG,
      COMMON_CODE_REG_MSG,
      showVisible: false,
      formData: {},
      activeTab: defaultTab,
      positionTab: defaultPositionTab,
      bodyTypeTab: defaultBodyTypeTab,
      serverUrl: "",
      httpServiceList: [],
      callback: () => {},
    };
  },

  computed: {
    isNew() {
      return !this.formData.id;
    },
  },
  methods: {
    open(data = {}, callback) {
      this.showVisible = true;
      this.callback = callback;
      this.formData = {
        ...data,
      };
      // 获取默认的httpServiceId
      if (
        !this.formData.id &&
        !this.formData.httpServiceId &&
        this.modelInfo.httpServiceId
      ) {
        this.$set(this.formData, "httpServiceId", this.modelInfo.httpServiceId);
      }
      this.activeTab = defaultTab;
      this.positionTab = defaultPositionTab;
      this.bodyTypeTab = defaultBodyTypeTab;

      this.$nextTick(() => {
        this.$refs.form.clearValidate();

        this.$refs.HttpQueryTable.setData(data.query);
        this.$refs.HttpReqBody.setData({
          bodyType: data.bodyType,
          body: data.body,
        });
        this.$refs.HttpHeaderTable.setData(data.header);
        this.$refs.HttpResTable.setData(data.response);
      });

      // this.loadHttpServiceInfo()
      this.loadHttpServiceList();
    },

    close() {
      this.showVisible = false;
    },

    handleTypeChange(val = "") {
      if (val === this.SERVICE_TYPE_OTHER) {
        this.$set(this.formData, "key", undefined);
        return;
      }
      const key = val
        .toLocaleLowerCase()
        .split("_")
        .map((item, index) =>
          index === 0 ? item : item.slice(0, 1).toUpperCase() + item.slice(1)
        )
        .join("");
      this.$set(this.formData, "key", key);
    },
    // 根据httpServiceId获取第三方服务的serverUrl
    loadHttpServiceInfo() {
      const { httpServiceId } = this.modelInfo;
      if (!httpServiceId) {
        return;
      }
      getHmhttpserviceInfo({
        id: httpServiceId,
      }).then((res) => {
        const devInfo = res.settingList.find((item) => item.env === "DEV");
        if (devInfo) {
          this.serverUrl = devInfo.serverUrl;
        }
      });
    },

    async curFormValidate() {
      try {
        await this.$refs.form.validate();
        return true;
      } catch (error) {
        console.log(error);
        return false;
      }
    },
    loadHttpServiceList() {
      getHmhttpservicePageList({ pageSize: 100000 }).then((res) => {
        this.httpServiceList = res.data;
      });
    },
    getServiceUrl(settingList) {
      const devInfo = settingList.find((item) => item.env === "DEV");
      if (devInfo) {
        return devInfo.serverUrl;
      }
    },
    async submit(flag = "") {
      try {
        const [
          formDataTrue,
          httpQueryTableData,
          httpReqBodyData,
          httpHeaderTableData,
          httpResTableData,
        ] = await Promise.all([
          this.curFormValidate(),
          this.$refs.HttpQueryTable.getData(),
          this.$refs.HttpReqBody.getData(),
          this.$refs.HttpHeaderTable.getData(),
          this.$refs.HttpResTable.getData(),
        ]);
        if (httpQueryTableData === false) {
          this.activeTab = "REQUEST";
          this.positionTab = "QUERY";
          return;
        } else if (httpReqBodyData === false) {
          this.activeTab = "REQUEST";
          this.positionTab = "BODY";
          return;
        } else if (httpHeaderTableData === false) {
          this.activeTab = "REQUEST";
          this.positionTab = "HEADERS";
          return;
        } else if (httpResTableData === false) {
          this.activeTab = "RESPONSE";
          return;
        }

        if (!formDataTrue) {
          return;
        }

        let params = {};
        let request = null;

        const { id, type, key, name, remark, method, path, httpServiceId } =
          this.formData;
        if (this.isNew) {
          request = postHmhttprequestdefinition;
          params = {
            type,
            key,
            name,
            remark,
            method,
            path,
            httpServiceId,
            serviceType: "HTTP",
            modelId: this.modelInfo.id,
          };
        } else {
          request = putHmhttprequestdefinition;
          params = { id, name, remark, method, httpServiceId, path };
        }
        for (const key in params) {
          params[key] =
            typeof params[key] === "string" ? params[key].trim() : params[key];
        }

        params.path =
          params.path?.length < 128 && !params.path.startsWith("/")
            ? `/${params.path}`
            : params.path;

        params.query = httpQueryTableData;
        params.header = httpHeaderTableData;
        params.body = httpReqBodyData.body;
        params.bodyType = httpReqBodyData.bodyType;
        params.response = httpResTableData;

        request(params)
          .then((res) => {
            this.showVisible = false;
            this.callback();
          })
          .finally(() => {
            if (flag === "debug") {
              this.$refs.HttpDebugModal.open({
                ...params,
              });
            }
          });
      } catch (error) {
        console.log(error);
        return false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form-item.method {
  width: 160px;

  ::v-deep .el-input__inner {
    border-bottom-right-radius: 0;
    border-top-right-radius: 0;
  }
}

.el-form-item.path {
  flex: 1;

  ::v-deep .el-input-group__prepend {
    border-bottom-left-radius: 0;
    border-top-left-radius: 0;
    border-left: none;
  }
}

.request-tabs {
  ::v-deep .el-tabs__header {
    margin-right: 20px;
  }
}
</style>
